package com.itheima.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.itheima.pojo.Result;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// 定义一个拦截器
@Component  // 将当前类的对象交给IOC容器管理
public class LoginCheckInterceptor implements HandlerInterceptor {
//    @Override
//    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        System.out.println("preHandle...");
////        return false;   // 不放行
//        return true;   // 放行
//    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.获取请求url
        String url = request.getRequestURL().toString();

        // 2.判断请求url中是否包含login，如果包含，证明是登录请求，放行
//        if (url.contains("login")) {
//            // 放行
//            return true;
//        }

        // 3.不是登录请求，获取请求头中的token
        String jwt = request.getHeader("token");

        // 4.判断令牌是否存在，如果不存在，返回错误结果
        if (!StringUtils.hasLength(jwt)) {
            Result result = Result.error("NOT_LOGIN");
            // 借助于FastJson工具类将对象转换成Json字符串
            String jsonString = JSONObject.toJSONString(result);
            response.getWriter().println(jsonString);
            return false;   // 不放行
        }

        // 5.证明有令牌，解析令牌
        try {
            Claims claims = JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            response.getWriter().println(JSONObject.toJSONString(Result.error("NOT_LOGIN")));
            return false;   // 不放行
        }

        // 6.解析令牌没报错，放行
        return true;
    }



    /*@Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle...");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion...");
    }*/
}
